package com.student_exam_system.controller;

import com.alibaba.fastjson.JSON;
import com.student_exam_system.Util.JwtUtil;
import com.student_exam_system.config.ConstMsg;
import com.student_exam_system.pojo.Msg;
import com.student_exam_system.pojo.UserPaper;
import com.student_exam_system.service.UserPaperService;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import javax.servlet.http.HttpServletRequest;
import java.sql.Timestamp;


/**
 * @author fire'ge
 */
@Controller
public class UserPaperController {
    final
    UserPaperService userPaperService;

    public UserPaperController(@Qualifier("userPaperServiceImpl") UserPaperService userPaperService) {
        this.userPaperService = userPaperService;
    }


    @PreAuthorize("hasAuthority('student')")
    @ResponseBody
    @RequestMapping(value = "/userPaper/confirmFinish",produces = "application/json;charset=utf-8")
    public String confirmFinish( HttpServletRequest request) {

        String token = request.getHeader("token");
            int userId = JwtUtil.getJWTUserId(token);
        int update = userPaperService.updateUserPaper(userId);
        if (update==0){
            throw new RuntimeException("修改userPaper关系表时出现了异常");
        }

        Msg msg = new Msg(ConstMsg.CONFIRM_MSG, new Timestamp(System.currentTimeMillis()));
        request.getSession().removeAttribute("paperId");
       return JSON.toJSONString(msg);

    }

    @PreAuthorize("hasAuthority('student')")
    @RequestMapping(value = "/userPaper/addUserPaper",produces = "application/json;charset=utf-8")
    public String addUserPaper(HttpServletRequest request) {
        int paperId = (int)request.getSession().getAttribute("paperId");
        String token = request.getHeader("token");

            int userId = JwtUtil.getJWTUserId(token);
        int insert = userPaperService.addUserPaper(new UserPaper(0, paperId, userId, 0, 0));
        if (insert==0){
            throw new RuntimeException("增加userPaper关系表时候出现了错误");
        }
        return "forward:/showQueData"+ ConstMsg.KEY_PARAM;
    }
}
